package urban;

import java.util.ArrayList;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 */

/**
 * @author emily
 *
 */
public class Letter extends StringObject {

	public String letter;
	ArrayList<Word> words = new ArrayList<Word>();

	public Letter(String letter) throws XMLStreamException {
		this.letter = letter;
		new Thread(this).start();
	}

	@SuppressWarnings("static-access")
	public void fillEventInfo(XMLStreamReader reader) throws XMLStreamException {
		int eventCode = reader.next();
		if (eventCode == 1 && reader.getLocalName().equals("a")
				&& reader.getAttributeValue(1) != null
				&& reader.getAttributeValue(1).equals("hoverable_entry")) {
			while (true) {
				eventCode = reader.next();
				if (eventCode == reader.CHARACTERS) {
					String t = reader.getText();
					t = t.trim();
					if (!t.equalsIgnoreCase(this.letter) && !t.contains(" ")) {
						Word w = new Word(t);
						words.add(w);
					}
					break;
				}
			}
		}
		reader.close();
	}

	public ArrayList<Word> getArrayList() {
		return this.words;
	}

	public String toString() {
		return this.letter;
	}

	@Override
	public void run() {
		// Start timer.
//		long start = System.currentTimeMillis();
//		System.out.println("Letter thread starting.");
		int i = 18;
		boolean flag = true;
		if(letter.equalsIgnoreCase("B")) i = 20;
		while(flag) {
			String link = "http://www.urbandictionary.com/browse.php?character="+letter+"&page="+i;
			try {
				flag = populate(link);
			} catch (XMLStreamException e) {
				System.err.println("There was an XMLStreamException in Letter. Boo :(");
			}
			i++;
			flag = false;
		}
		System.out.println("Letter: "+this.letter+" Total Words: "+words.size());
		// Print timer.
//		long finish = System.currentTimeMillis();
//		System.out.println("Total Time: "+(finish-start));
	}
}
